package stu.day25_day32.day32;

public class hw1 {

    public void solve(char[][] board) {

        int n = board.length;
        int m = board[0].length;

        for(int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                if(i==0||i==n-1||j==0||j==m-1){
                        dfs1(i,j,board);
                }
            }
        }

        for(int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                if(board[i][j]=='O'){
                    board[i][j]='X';
                }
            }
        }

        for(int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                if(board[i][j]=='N'){
                    board[i][j]='O';
                }
            }
        }


    }

    public void dfs1(int i,int j,char[][] board){
        if(i>=0&&i<board.length&&j>=0&&j<board[0].length){
            if(board[i][j]=='O'){
                board[i][j]='N';
                dfs1(i+1,j,board);
                dfs1(i-1,j,board);
                dfs1(i,j+1,board);
                dfs1(i,j-1,board);
            }

        }
    }



    public int islandPerimeter(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;

        for(int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                if(grid[i][j]==1){
                    return dfs2(i,j,n,m,grid);
                }
            }
        }
        return 0;

    }


    public int dfs2(int i,int j,int n,int m,int[][] grid){
        if(i>=0&&i<n&&j>=0&&j<m){
            if(grid[i][j]==1){
                grid[i][j]=2;
                return dfs2(i+1,j,n,m,grid)+dfs2(i-1,j,n,m,grid)+dfs2(i,j+1,n,m,grid)+dfs2(i,j-1,n,m,grid);
            } else if (grid[i][j]==0) {
                return 1;
            }else{
                return 0;
            }
        }else{
            return 1;
        }
    }


    public int max=0;
    public int maxAreaOfIsland(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;

        for(int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                if(grid[i][j]==1){
                    max=Math.max(max,dfs3(i,j,n,m,grid));
                }
            }
        }
        return max;
    }


    public int dfs3(int i,int j,int n,int m,int[][] grid){
        if(i>=0&&i<n&&j>=0&&j<m){
            if(grid[i][j]==1){
                grid[i][j]=2;
                return dfs3(i+1,j,n,m,grid)+dfs3(i-1,j,n,m,grid)+dfs3(i,j+1,n,m,grid)+dfs3(i,j-1,n,m,grid)+1;
            }
            else {
                return 0;
            }
        }
        return 0;
    }

}
